<%@ page import="main.java.com.entity.Dish" %>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>菜品管理系统</title>
    <style>
        body {
            text-align: center;
        }

        table {
            border-collapse: collapse;
            width: 80%;
            margin: auto;
        }

        th,
        td {
            border: 1px solid #ccc;
            padding: 8px;
        }

        tr:nth-child(even) {
            background-color: #f2f2f2;
        }

        th {
            font-weight: bold;
        }

        a {
            text-decoration: none;
            color: blue;
        }

        form {
            margin-bottom: 10px;
        }

        input[type="text"] {
            padding: 5px;
        }

        button {
            padding: 5px 10px;
            background-color: #333;
            color: white;
            border: none;
            cursor: pointer;
        }

        .batch-operation-buttons button {
            margin: 0 10px;
            padding: 5px 15px;
            background-color: #007bff;
            color: white;
            border: none;
            cursor: pointer;
        }

        /* 现有样式 */
        .batch-operation-buttons {
            margin-top: 10px;
            display: flex;
            justify-content: flex-end;
            margin-right:150px;
        }


        .pagination {
            margin-top: 10px;
            display: flex;
            justify-content: center;
        }

        .pagination a {
            margin: 0 5px;
            padding: 5px 10px;
            border: 1px solid #ccc;
        }

        .active {
            background-color: #333;
            color: white;
        }

        .operation-buttons {
            display: flex;
            justify-content: space-around;
        }

        .operation-buttons button {
            margin: 0 5px;
        }

        /* 添加按钮的样式 */
        .add-button {
            margin-top: 10px;
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
    </style>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js" ></script>
    <script type="text/javascript">
        // 当文档加载完成时执行的函数
        $(document).ready(function () {
            // 搜索功能
            $("#searchForm").submit(function (e) {
                e.preventDefault();
                var keyword = $("#keyword").val();
                var status = $("#status").val();
                window.location.href = "DishListServlet?keyword=" + encodeURIComponent(keyword) + "&status=" + status;
            });

            // 分页功能
            function renderPagination(totalPages, currentPage) {
                var paginationHtml = "";
                paginationHtml += '<a href="DishListServlet?page=1&keyword=${keyword}&status=${status}" class="first-page">首页</a>';
                if (currentPage > 1) {
                    paginationHtml += '<a href="DishListServlet?page=' + (currentPage - 1) + '&keyword=${keyword}&status=${status}" class="prev-page">上一页</a>';
                }
                for (var i = 1; i <= totalPages; i++) {
                    if (i === currentPage) {
                        paginationHtml += '<a class="active" href="DishListServlet?page=' + i + '&keyword=${keyword}&status=${status}">' + i + '</a>';
                    } else {
                        paginationHtml += '<a href="DishListServlet?page=' + i + '&keyword=${keyword}&status=${status}">' + i + '</a>';
                    }
                }
                if (currentPage < totalPages) {
                    paginationHtml += '<a href="DishListServlet?page=' + (currentPage + 1) + '&keyword=${keyword}&status=${status}" class="next-page">下一页</a>';
                }
                paginationHtml += '<a href="DishListServlet?page=' + totalPages + '&keyword=${keyword}&status=${status}" class="last-page">末页</a>';
                paginationHtml += '<input type="number" min="1" max="' + totalPages + '" value="' + currentPage + '" class="jump-input" placeholder="跳转至页码">';
                paginationHtml += '<button class="jump-button">跳转</button>';
                $(".pagination").html(paginationHtml);
            }

            // 页面加载时渲染分页
            var totalCount = ${totalCount};
            var pageSize = ${pageSize};
            var totalPages = ${totalPages};
            var currentPage = ${page};
            renderPagination(totalPages, currentPage);

            // 点击首页、上一页、下一页、末页按钮的事件处理
            $(".pagination").on("click", ".first-page,.prev-page,.next-page,.last-page", function (e) {
                e.preventDefault();
                var targetPage = 1;
                if ($(this).hasClass("prev-page")) {
                    targetPage = currentPage - 1;
                } else if ($(this).hasClass("next-page")) {
                    targetPage = currentPage + 1;
                } else if ($(this).hasClass("last-page")) {
                    targetPage = totalPages;
                }
                window.location.href = "DishListServlet?page=" + targetPage + "&keyword=${keyword}&status=${status}";
            });

            // 点击跳转按钮的事件处理
            $(".pagination").on("click", ".jump-button", function (e) {
                e.preventDefault();
                var targetPage = parseInt($(".jump-input").val());
                if (!isNaN(targetPage) && targetPage >= 1 && targetPage <= totalPages) {
                    window.location.href = "DishListServlet?page=" + targetPage + "&keyword=${keyword}&status=${status}";
                } else {
                    alert("请输入有效的页码！");
                }
            });

            // 启用/禁用操作
            $(".enable-disable-button").click(function () {
                var dishId = $(this).data("dish-id");
                var newStatus = $(this).data("new-status");
                if (confirm("确定要更改菜品状态吗？")) {
                    $.ajax({
                        url: "UpdateDishStatusServlet",
                        type: "GET",
                        data: {
                            id: dishId,
                            status: newStatus
                        },
                        success: function (response) {
                            if (response === "success") {
                                alert("操作成功！");
                                location.reload();
                            } else {
                                alert("操作失败，请重试！");
                            }
                        },
                        error: function () {
                            alert("请求出错，请检查网络或稍后重试！");
                        }
                    });
                }
            });


            // 修改操作
            $(".edit-button").click(function () {
                var dishId = $(this).data("dish-id");
                window.location.href = "EditDishServlet?id=" + dishId;
            });

            // 删除操作
            $(".delete-button").click(function () {
                var dishId = $(this).data("dish-id");
                if (confirm("确定要删除该菜品吗？")) {
                    $.ajax({
                        url: "DeleteDishServlet",
                        type: "GET",
                        data: {
                            id: dishId
                        },
                        success: function (response) {
                            var deleteResult = parseInt(response);
                            if (deleteResult > 0) {
                                alert("删除成功！");
                                location.reload(); // 刷新页面以显示最新的菜品列表
                            } else {
                                alert("删除失败，请检查网络或联系管理员！");
                            }
                        },
                        error: function () {
                            alert("请求出错，请检查网络或稍后重试！");
                        }
                    });
                }
            });

            // 批量删除操作
            $(".batch-delete-button").click(function () {
                var selectedDishIds = [];
                $("input[name='dishId']:checked").each(function () {
                    selectedDishIds.push($(this).val());
                });

                if (selectedDishIds.length === 0) {
                    alert("请选择要删除的菜品！");
                    return;
                }

                if (confirm("确定要删除选中的菜品吗？")) {
                    $.ajax({
                        url: "BatchDeleteDishServlet",
                        type: "POST",
                        data: {
                            ids: selectedDishIds.join(",")
                        },
                        success: function (response) {
                            var deleteResult = parseInt(response);
                            if (deleteResult > 0) {
                                alert("删除成功！");
                                location.reload();
                            } else {
                                alert("删除失败，请检查网络或联系管理员！");
                            }
                        },
                        error: function () {
                            alert("请求出错，请检查网络或稍后重试！");
                        }
                    });
                }
            });

            // 全选/取消全选功能
            $("#selectAllCheckbox").click(function () {
                var isChecked = $(this).is(":checked");
                $("input[name='dishId']").prop("checked", isChecked);
            });

            // 批量启售操作
            $(".batch-enable-button").click(function () {
                var selectedDishIds = [];
                $("input[name='dishId']:checked").each(function () {
                    selectedDishIds.push($(this).val());
                });

                if (selectedDishIds.length === 0) {
                    alert("请选择要启售的菜品！");
                    return;
                }

                if (confirm("确定要启售选中的菜品吗？")) {
                    $.ajax({
                        url: "BatchUpdateDishStatusServlet",
                        type: "POST",
                        data: {
                            ids: selectedDishIds.join(","),
                            status: 1
                        },
                        success: function (response) {
                            var updateResult = parseInt(response);
                            if (updateResult > 0) {
                                alert("启售成功！");
                                location.reload();
                            } else {
                                alert("启售失败，请检查网络或联系管理员！");
                            }
                        },
                        error: function () {
                            alert("请求出错，请检查网络或稍后重试！");
                        }
                    });
                }
            });

            // 批量停售操作
            $(".batch-disable-button").click(function () {
                var selectedDishIds = [];
                $("input[name='dishId']:checked").each(function () {
                    selectedDishIds.push($(this).val());
                });

                if (selectedDishIds.length === 0) {
                    alert("请选择要停售的菜品！");
                    return;
                }

                if (confirm("确定要停售选中的菜品吗？")) {
                    $.ajax({
                        url: "BatchUpdateDishStatusServlet",
                        type: "POST",
                        data: {
                            ids: selectedDishIds.join(","),
                            status: 0
                        },
                        success: function (response) {
                            var updateResult = parseInt(response);
                            if (updateResult > 0) {
                                alert("停售成功！");
                                location.reload();
                            } else {
                                alert("停售失败，请检查网络或联系管理员！");
                            }
                        },
                        error: function () {
                            alert("请求出错，请检查网络或稍后重试！");
                        }
                    });
                }
            });

        });
    </script>
</head>

<body>
<main style="padding: 20px;">
    <h1>菜品管理系统</h1>
    <form id="searchForm" action="DishListServlet" method="post">
        <input type="text" id="keyword" placeholder="请输入菜品名称或商品码进行搜索" value="${keyword}">
        <select id="status">
            <option value="" ${status == null? 'selected' : ''}>全部状态</option>
            <option value="0" ${status == 0? 'selected' : ''}>停售</option>
            <option value="1" ${status == 1? 'selected' : ''}>起售</option>
        </select>
        <button type="submit">搜索</button>
        <a href="AddDishServlet" class="add-button">添加</a>
    </form>
    <div class="batch-operation-buttons">
        <button class="batch-enable-button">批量启售</button>
        <button class="batch-disable-button">批量停售</button>
        <button class="batch-delete-button">批量删除</button>
    </div>
    <table>
        <tr>
            <th><input type="checkbox" id="selectAllCheckbox"></th>
            <th>菜单名称</th>
            <th>图片</th>
            <th>菜品分类</th>
            <th>售价</th>
            <th>售卖状态</th>
            <th>最后操作时间</th>
            <th>操作</th>
        </tr>
        <%
            List<Dish> dishes = (List<Dish>) request.getAttribute("dishes");
            if (dishes!= null) {
                for (Dish dish : dishes) {
        %>
        <tr>
            <td><input type="checkbox" name="dishId" value="<%=dish.getId()%>"></td>
            <td><%=dish.getName()%></td>
            <td><img src="backend/image/<%=dish.getImage()%>" alt="菜品图片" width="50px" height="50px"></td>
            <td><%=dish.getCategoryName()%></td>
            <td><%=dish.getPrice()%></td>
            <td><%=dish.getStatus() == 1? "启售" : "停售"%></td>
            <td><%=dish.getUpdate_time()%></td>
            <td>
                <div class="operation-buttons">
                    <button class="enable-disable-button" data-dish-id="<%=dish.getId()%>" data-new-status="<%=dish.getStatus() == 1? 0 : 1%>"><%=dish.getStatus() == 1? "禁用" : "启用"%></button>
                    <button class="edit-button" data-dish-id="<%=dish.getId()%>">修改</button>
                    <button class="delete-button" data-dish-id="<%=dish.getId()%>">删除</button>
                </div>
            </td>
        </tr>
        <%
                }
            }
        %>
    </table>
    <div class="pagination"></div>
</main>
</body>

</html>